package com.lagou.esweb.mvc.service;

import com.lagou.esweb.common.Response;
import com.lagou.esweb.mvc.doc.PositionDoc;
import com.lagou.esweb.mvc.repository.PositionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public final class PositionService {

    final ElasticsearchRestTemplate elasticsearchRestTemplate;

    final RestHighLevelClient restHighLevelClient;

    final PositionRepository positionRepository;

    public Response<List<PositionDoc>> list(String positionName) {
        CriteriaQuery query = new CriteriaQuery(Criteria.where("positionName").matches(positionName));
        SearchHits<PositionDoc> searchHits = elasticsearchRestTemplate.search(query, PositionDoc.class);
        List<PositionDoc> positionDocs = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        if (searchHits.getTotalHits() < 5) {
            Set<Long> ids = positionDocs.stream().map(PositionDoc::getId).collect(Collectors.toSet());
            log.info("查询数量:{}", searchHits.getTotalHits());
            SearchHits<PositionDoc> hits = elasticsearchRestTemplate.search(new CriteriaQuery(Criteria.where("positionAdvantage").matches("美女多")), PositionDoc.class);
            log.info("推荐查询数据:{}", hits.getTotalHits());
            positionDocs.addAll(hits.stream().map(SearchHit::getContent).filter(doc -> !ids.contains(doc.getId())).map(doc -> {
                doc.setCompanyName("推荐==>" + StringUtils.trimToEmpty(doc.getCompanyName()));
                return doc;
            }).collect(Collectors.toList()));
        }
        return Response.OK(positionDocs);
    }
}
